/*
 * Copyright 2025 The JA-SIG Collaborative. All rights reserved.
 * distributed with this file and available online at
 */
package com.lap.auth.adapter.driving.persistence.tenant.repository;

import com.lap.auth.adapter.driving.persistence.tenant.TenantConverter;
import com.lap.auth.adapter.driving.persistence.tenant.mapper.TenantMapper;
import com.lap.auth.adapter.driving.persistence.tenant.po.TenantPo;
import com.lap.auth.domain.tenant.Tenant;
import com.lap.auth.domain.tenant.repository.TenantRepository;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;

@RequiredArgsConstructor
@Repository
public class TenantRepositoryImpl implements TenantRepository {

  private final TenantConverter tenantConverter;
  private final TenantMapper tenantMapper;

  @Override
  public Integer save(Tenant tenant) {
    TenantPo tenantPo = tenantConverter.toPo(tenant);
    if (tenant.isNew()) {
      tenantMapper.insert(tenantPo);
      return tenantPo.getId();
    }
    return tenantMapper.updateByPrimaryKey(tenantPo);
  }

  @Override
  public int deleteById(Integer id) {
    return tenantMapper.deleteByPrimaryKey(id);
  }

  @Override
  public Optional<Tenant> findById(Integer id) {
    var tenantPo = tenantMapper.selectByPrimaryKey(id);
    return Optional.ofNullable(tenantConverter.toDomain(tenantPo));
  }
}
